<template>
  <el-dialog
      :title="isEdit ? '编辑老人' : '添加老人'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="elder-form"
    >
      <el-form-item label="姓名" prop="elderName">
        <el-input v-model="form.elderName" placeholder="请输入老人姓名"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="form.password"
            type="password"
            :placeholder="isEdit ? '不修改请留空' : '请输入密码'"
            show-password
        />
      </el-form-item>
      <el-form-item label="所属社区" prop="communityId">
        <el-select
            v-model="form.communityId"
            placeholder="选择社区"
            filterable
            remote
            :remote-method="filterCommunity"
            :loading="communityLoading"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="item in filteredCommunityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8080/File/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, watch, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import type {FormInstance} from 'element-plus'
import type {Elder} from '@/types/elder'
import type {Community} from '@/types/community'
import {addElder, updateElder} from '@/api/elder'
import {useUserStore} from '@/stores/user'

const props = defineProps<{
  modelValue: boolean
  elder?: Elder
  communityList: Community[]
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const userStore = useUserStore()

// 上传相关
const uploadHeaders = computed(() => ({
  Authorization: userStore.token
}))

const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])


// 创建一个新的响应式表单数据
const form = reactive<Partial<Elder>>({
  id: undefined,
  elderName: '',
  phone: '',
  password: '',
  communityId: undefined,
  avatar: ''
})

// 监听 elder prop 的变化
watch(() => props.elder, (newVal) => {
  if (newVal) {
    // 设置表单数据，密码字段为空
    const {password, ...rest} = newVal
    Object.assign(form, {
      ...rest,
      password: '' // 编辑时密码默认为空
    })
    // 关键修改：确保社区名称显示
    if (newVal.communityId) {
      const selectedCommunity = props.communityList.find(
          c => c.id === newVal.communityId
      )
      if (selectedCommunity) {
        filteredCommunityList.value = [selectedCommunity, ...props.communityList]
      }
    }
  } else {
    // 重置表单数据
    Object.assign(form, {
      id: undefined,
      elderName: '',
      phone: '',
      password: '',
      communityId: undefined,
      avatar: ''
    })
  }
}, {immediate: true})

// 监听社区列表变化
watch(() => props.communityList, (newVal) => {
  filteredCommunityList.value = [{id: 0, name: '无'}, ...newVal]

  // 如果当前有选中的社区ID，确保它在列表中
  if (form.communityId) {
    const selectedCommunity = newVal.find(c => c.id === form.communityId)
    if (selectedCommunity && !filteredCommunityList.value.some(c => c.id === selectedCommunity.id)) {
      filteredCommunityList.value = [selectedCommunity, ...newVal]
    }
  }
}, {immediate: true})

// 监听对话框显示状态
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    // 关闭对话框时重置表单
    handleClose()
  } else if (props.elder) {
    // 当对话框打开且有 elder 数据时，更新表单
    const {password, ...rest} = props.elder
    Object.assign(form, {
      ...rest,
      password: '' // 编辑时密码默认为空
    })
  }
})

// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = props.communityList.filter(item => {
        return item.name.includes(query)
      })

      // 确保当前选中的社区在列表中
      if (form.communityId) {
        const selectedCommunity = props.communityList.find(c => c.id === form.communityId)
        if (selectedCommunity && !filteredCommunityList.value.some(c => c.id === selectedCommunity.id)) {
          filteredCommunityList.value = [selectedCommunity, ...filteredCommunityList.value]
        }
      }

      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = [...props.communityList]
  }
}


// 创建表单校验规则
const getRules = (isEdit: boolean) => ({
  elderName: [
    {required: false, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  password: [
    {required: !isEdit, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/,
      min: 6,
      message: '请输入正确的密码（6位及以上字母+数字组合）',
      trigger: ['blur', 'change']
    }
  ],
  communityId: [
    {required: false, message: '请选择所属社区', trigger: 'change'}
  ]
})

const rules = computed(() => getRules(props.isEdit))

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保所有必需字段都存在
        if (!form.elderName || !form.phone) {
          ElMessage.error('请填写所有必需字段')
          return
        }

        const submitData: Elder = {
          id: props.isEdit ? (props.elder?.id || 0) : 0,
          elderName: form.elderName,
          phone: form.phone,
          password: form.password || '',
          communityId: form.communityId,
          avatar: form.avatar || ''
        }

        // 如果是编辑模式且密码为空，则使用原始密码
        if (props.isEdit && !submitData.password) {
          submitData.password = props.elder?.password || ''
        }

        // 调用API
        if (props.isEdit) {
          await updateElder(submitData)
          ElMessage.success('更新成功')
        } else {
          await addElder(submitData)
          ElMessage.success('添加成功')
        }

        // 关闭对话框并触发成功事件
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    form.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '头像上传失败')
  }
}

// 头像上传失败
const handleAvatarError = (error: any) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 头像上传前校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 20

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!')
  }
  return isJPG && isLt2M
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 清空表单数据
  Object.assign(form, {
    id: undefined,
    elderName: '',
    phone: '',
    password: '',
    communityId: undefined,
    avatar: ''
  })
}

defineExpose({
  open
})
</script>

<style scoped>
.elder-form {
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border-radius: 50%;
}
</style> 